//
//  HttpRequest.m
//  NewDemo
//
//  Created by Andy_chen on 11/16/15.
//  Copyright © 2015 Andycchen. All rights reserved.
//

#import "HttpRequest.h"
#import "DataParser.h"

@interface HttpRequest()
@property(nonatomic, assign)NSInteger timeInternal;

/**
 *  取消指定的AFNetworking的网络请求
 *
 *  @param requestUrl 指定的请求URL
 */
- (BOOL)cancelAppointedRequest:(NSString *)requestUrl;

/**
 *  请求成功 统一检测口
 *
 *  @param operation 请求线程
 *  @param response  响应返回数据
 */
-(void)requestSuccess:(AFHTTPRequestOperation *)operation response:(id)response;

/**
 *  请求失败 统一检测口
 *
 *  @param error 错误信息
 */
-(void)requestFail:(NSError*)error;

@end

@implementation HttpRequest
@synthesize requestUrl = _requestUrl;
@synthesize timeInternal = _timeInternal;

#pragma mark - request methods

- (void)getHTMLDataWithUrl:(NSString *)URLString
                parameters:(NSDictionary *)parameters
                   success:(void(^)(AFHTTPRequestOperation *operation, id responseObject))success
                   failure:(void(^)(NSError * error))failure;
{
    //防止重复请求
    [self cancelAppointedRequest:URLString];
    self.success = success;
    self.failure = failure;
    
    [self printfUseUpSystemTime:YES];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:URLString
      parameters:parameters
         success:^(AFHTTPRequestOperation *operation, id responseObject) {
             [self requestSuccess:operation response:responseObject];
         }
         failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             [self requestFail:error];
         }];
}

- (void)postHTMLDataWithUrl:(NSString *)URLString
                 parameters:(NSDictionary *)parameters
                    success:(void(^)(AFHTTPRequestOperation *operation, id responseObject))success
                    failure:(void(^)(NSError * error))failure;
{
    //防止重复请求
    [self cancelAppointedRequest:URLString];
    self.success = success;
    self.failure = failure;
    
    [self printfUseUpSystemTime:YES];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:URLString
       parameters:parameters
          success:^(AFHTTPRequestOperation *operation, id responseObject) {
              NSString* dataString = [[NSString alloc]initWithData:(NSData *)responseObject encoding:NSUTF8StringEncoding];
              [self requestSuccess:operation response:dataString];
          }
          failure:^(AFHTTPRequestOperation *operation, NSError *error) {
              [self requestFail:error];
          }];
}


- (void)getJSONDataWithUrl:(NSString *)URLString
                parameters:(NSDictionary *)parameters
                   success:(void(^)(AFHTTPRequestOperation *operation, id responseObject))success
                   failure:(void(^)(NSError * error))failure;
{
    //防止重复请求
    [self cancelAppointedRequest:URLString];
    self.success = success;
    self.failure = failure;
    
    [self printfUseUpSystemTime:YES];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager GET:URLString
      parameters:parameters
         success:^(AFHTTPRequestOperation *operation, id responseObject) {
             NSDictionary* parseData = [NSDictionary dictionaryFromJSONData:responseObject];
             [self requestSuccess:operation response:parseData];
         }
         failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             [self requestFail:error];
         }];
}

- (void)postJSONDataWithUrl:(NSString *)URLString
                 parameters:(NSDictionary *)parameters
                    success:(void(^)(AFHTTPRequestOperation *operation, id responseObject))success
                    failure:(void(^)(NSError * error))failure;
{
    //防止重复请求
    [self cancelAppointedRequest:URLString];
    self.success = success;
    self.failure = failure;
    
    [self printfUseUpSystemTime:YES];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager POST:URLString
       parameters:parameters
          success:^(AFHTTPRequestOperation *operation, id responseObject) {
              NSDictionary* parseData = [NSDictionary dictionaryFromJSONData:responseObject];
              [self requestSuccess:operation response:parseData];
          }
          failure:^(AFHTTPRequestOperation *operation, NSError *error) {
              [self requestFail:error];
          }];
}

- (void)getXMLDataWithUrl:(NSString *)URLString
               parameters:(NSDictionary *)parameters
                  success:(void(^)(AFHTTPRequestOperation *operation, id responseObject))success
                  failure:(void(^)(NSError * error))failure;
{
    //防止重复请求
    [self cancelAppointedRequest:URLString];
    self.success = success;
    self.failure = failure;
    
    [self printfUseUpSystemTime:YES];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager GET:URLString
      parameters:parameters
         success:^(AFHTTPRequestOperation *operation, id responseObject) {
             NSData* responseData = [NSData dataWithData:(NSData *)(responseObject)];
             XMLParser  *xmlParser = [[XMLParser alloc] init];
             [xmlParser parseData:responseData
                          success:^(id parsedData) {
                              [self requestSuccess:operation response:parsedData];
                          }
                          failure:^(NSError *error) {
                              [self requestFail:error];
                          }];
         }
         failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             [self requestFail:error];
         }];
}

- (void)postXMLDataWithUrl:(NSString *)URLString
                parameters:(NSDictionary *)parameters
                   success:(void(^)(AFHTTPRequestOperation *operation, id responseObject))success
                   failure:(void(^)(NSError * error))failure;
{
    //防止重复请求
    [self cancelAppointedRequest:URLString];
    self.success = success;
    self.failure = failure;
    
    [self printfUseUpSystemTime:YES];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:URLString
       parameters:parameters
          success:^(AFHTTPRequestOperation *operation, id responseObject) {
              NSData* responseData = [NSData dataWithData:(NSData *)(responseObject)];
              XMLParser  *xmlParser = [[XMLParser alloc] init];
              [xmlParser parseData:responseData
                           success:^(id parsedData) {
                               [self requestSuccess:operation response:parsedData];
                           }
                           failure:^(NSError *error) {
                               [self requestFail:error];
                           }];
          }
          failure:^(AFHTTPRequestOperation *operation, NSError *error) {
              [self requestFail:error];
          }];
}

- (void)getImageDataWithUrl:(NSString *)URLString
                 parameters:(NSDictionary *)parameters
                    success:(void(^)(AFHTTPRequestOperation *operation, id responseObject))success
                    failure:(void(^)(NSError * error))failure;
{
    //防止重复请求
    [self cancelAppointedRequest:URLString];
    self.success = success;
    self.failure = failure;
    
    [self printfUseUpSystemTime:YES];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager.requestSerializer setTimeoutInterval:10];
    [manager GET:URLString
      parameters:parameters
         success:^(AFHTTPRequestOperation *operation, id responseObject) {
             UIImage* image = [UIImage imageWithData:(NSData *)responseObject];
             [self requestSuccess:operation response:image];
         }
         failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             [self requestFail:error];
         }];
}

- (void)postImageDataWithUrl:(NSString *)URLString
                  parameters:(NSDictionary *)parameters
                     success:(void(^)(AFHTTPRequestOperation *operation, id responseObject))success
                     failure:(void(^)(NSError * error))failure;
{
    //防止重复请求
    [self cancelAppointedRequest:URLString];
    self.success = success;
    self.failure = failure;
    
    [self printfUseUpSystemTime:YES];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:URLString
       parameters:parameters
          success:^(AFHTTPRequestOperation *operation, id responseObject) {
              UIImage* image = [UIImage imageWithData:(NSData *)responseObject];
              [self requestSuccess:operation response:image];
          }
          failure:^(AFHTTPRequestOperation *operation, NSError *error) {
              [self requestFail:error];
          }];
}

- (void)postMultiFormDataWithUrl:(NSString*)URLString
                        FormData:(NSData*)data
                         success:(void(^)(AFHTTPRequestOperation *operation, id responseObject))success
                         failure:(void(^)(NSError * error))failure;
{
    //防止重复请求
    [self cancelAppointedRequest:URLString];
    self.success = success;
    self.failure = failure;
    
    [self printfUseUpSystemTime:YES];
    
    NSMutableURLRequest *request = nil;
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager.requestSerializer setTimeoutInterval:60];
    request = [manager.requestSerializer multipartFormRequestWithMethod:@"POST"
                                                              URLString:URLString
                                                             parameters:nil
                                              constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
                                                  [formData appendPartWithFileData:data
                                                                              name:@"file"
                                                                          fileName:@"file.jpeg"
                                                                          mimeType:@"image/jpeg"];
                                              }
                                                                  error:nil];
    
    [manager HTTPRequestOperationWithRequest:request
                                     success:^(AFHTTPRequestOperation *operation, id responseObject) {
                                         NSDictionary* parseData = [NSDictionary dictionaryFromJSONData:responseObject];
                                         [self requestSuccess:operation response:parseData];
                                     }
                                     failure:^(AFHTTPRequestOperation *operation, NSError *error){
                                         [self requestFail:error];
                                     }];
}


#pragma mark - private methods
-(BOOL)isCancelled
{
    return _isCancelled;
}


- (void)cancelAFURLRequest
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    if (manager.operationQueue != nil) {
        [manager.operationQueue cancelAllOperations];
    }
}

- (void)requestCancel {
    _isCancelled = [self cancelAppointedRequest:_requestUrl];
}

- (BOOL)cancelAppointedRequest:(NSString *)requestUrl {
    
    BOOL cancelled = NO;
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    for (AFHTTPRequestOperation *operation in manager.operationQueue.operations) {
        if ([[operation.request.URL absoluteString] isEqualToString:requestUrl] ) {
            [operation cancel];
            cancelled = YES;
        }
    }
    return  cancelled;
}

#pragma mark - request response
-(void)requestSuccess:(AFHTTPRequestOperation *)operation response:(id)response
{
    //增加接口调用成功时response日志
    [self paLog: [NSString stringWithFormat: @""]];
    [self printfUseUpSystemTime:NO];
    self.success(operation,response);
}

-(void)requestFail:(NSError*)error
{
    //增加接口调用失败时response日志
    //TODO
    [self paLog: [NSString stringWithFormat:@""]];
    [self printfUseUpSystemTime:NO];
    
    //如果用户取消了请求，不提示请求失败
    if (_isCancelled) {
        return;
    }
    
    self.failure(error);
}

static NSDate *sdate;
#pragma mark 打印共消耗的系统时间
-(void)printfUseUpSystemTime:(BOOL)setOrget
{
    NSDate* dates = [NSDate date];
    NSDateFormatter *formatter=[[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss:SSS";
    NSString* nowTimeString = [formatter stringFromDate:dates];
    
    if (setOrget) {
        //开始设置起始时间
        sdate = [formatter dateFromString:nowTimeString];
        NSLog(@"\n============\n开始时间:%@\n=============\n",nowTimeString);
    }else{
        //打印时间差
        NSDate * endTime = [formatter dateFromString:nowTimeString];
        double deltaTime = [endTime timeIntervalSinceDate:sdate];
        
        NSLog(@"\n============\n开始时间:%@\n结束时间:%@\n消耗时间差:%.3f\n=============\n",[formatter stringFromDate:sdate], nowTimeString,deltaTime);
    }
}

-(void)paLog:(id)param {
    NSLog(@"-------[WE LOG INFO]-------\n%@", param);
}

@end
